//加载，当加载完了之后运行调用函数
window.addEventListener("load", eventWindowLoaded, false);

function eventWindowLoaded(){

	var theCanvas = document.getElementById("canvas");

	// 次数
	var guesses = 0;

	// 玩法
	var message = "guess the letter";

	var letterToGuess = "";

	var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y"];
	// 高或低
	var higherOrLower = "Please enter a letter~";
	// 已猜过的字母
	var lettersGuessed = "";

	var gameOver = false;

	var today = new Date();

	var btnRest = document.getElementById('btn-reset');
	btnRest.onclick = function (){
		initGame();
	};

	if(!theCanvas || !theCanvas.getContext){
		return;
	}

	var context = theCanvas.getContext("2d");

	function drawScreen(){
		// 背景
		context.fillStyle = "#ffffaa";
		context.fillRect(0, 0, 500, 300);
		// 边框
		context.strokeStyle = "#000000";
		context.strokeRect(5, 5, 490, 290);
		// 日期
		context.textBaseLine = "top"
		context.fillStyle = "#00000";
		context.font = "10px Sans-Serif";
		context.fillText(today, 150, 10);
		// 消息
		context.fillStyle = '#ff0000';
		context.font = "14px Sans-Serif";
		context.fillText(message, 125, 30)
		// 猜测的次数
		context.fillStyle = "#109910";
		context.font = "16px Sans-Serif";
		context.fillText('Guesses:' + guesses, 215, 50);
		// 显示highter/Lower
		context.fillStyle = "#000000";
		context.font = "16px Sans-Serif";
		context.fillText('Hight Or Lower:' + higherOrLower, 150, 125);
		// 猜过的字母
		context.fillStyle = '#ff0000';
		context.font = "16px Sans-Serif";
		context.fillText("Letters Guessed:" + lettersGuessed.toString(), 10, 260);
		//正确猜出后的提示
		if(gameOver){
			context.fillStyle = "#ff0000";
			context.font = "40px Sans-Serif";
			context.fillText('You Got it!', 150, 180);
		}
	}


	// 初始化游戏
	function initGame(){
		var letterIndex = Math.floor(Math.random() * letters.length)
		letterToGuess = letters[letterIndex];
		console.log(letterToGuess);

		guesses = 0;

		lettersGuessed = [];

		higherOrLower = "Please enter a letter~"

		gameOver = false;

		window.addEventListener("keydown", eventKeyPressed, true);
		drawScreen();
	}

	// 按键控制，并检测游戏
	function eventKeyPressed(e){
		if(!gameOver){
			var letterPressed = String.fromCharCode(e.keyCode);
			letterPressed = letterPressed.toLowerCase();
			guesses ++;
			lettersGuessed.push(letterPressed);

			if(letterPressed == letterToGuess){
				gameOver = true;
			}else{
				letterIndex = letters.indexOf(letterToGuess);
				guessIndex = letters.indexOf(letterPressed);
				if(guessIndex < 0){
					higherOrLower = "That is not a letter";
				}
				if(guessIndex < letterIndex){
					higherOrLower = "Lower";
				}else{
					higherOrLower = "Higher";
				}
			}	
			drawScreen();
		}
	}

	initGame();
}

	
